import React, { useState, useEffect, useRef } from 'react';
import { Button, Typography, message, Input } from 'antd';
import { RobotOutlined, SendOutlined, StopOutlined, PictureOutlined, CloseOutlined, CloudUploadOutlined } from '@ant-design/icons';
import { streamApiService, StreamMessage } from '../lib/researchReportApi';
import { uploadFile, validateFileType, validateFileSize, getFileTypeErrorMessage, getFileSizeErrorMessage } from '../lib/uploadApi';
import { renderMarkdownStreaming } from '../utils/markdown';
const { Title, Text } = Typography;
const { TextArea } = Input;

interface AIChatProps {
  title: string;
  uploadable?: boolean;
  style?: React.CSSProperties;
  propContent?: string;
  configApi?: any;
}
const AIChatModel: React.FC<AIChatProps> = ({title, uploadable, style, propContent,configApi}) =>  {
  const [aiAnalysis, setAiAnalysis] = useState<string>('');
  const [isStreaming] = useState(false);
  // 聊天相关状态
  const [chatInput, setChatInput] = useState('');
  const [isChatting, setIsChatting] = useState(false);
  const [chatHistory, setChatHistory] = useState<Array<{ type: 'user' | 'ai', content: string, timestamp: string }>>([]);
  const [chatStreamReply, setChatStreamReply] = useState<string>('');
  const [isAutoReplying] = useState(false); // 是否正在自动回复客户
  // AI功能开关
  const [aiUploadedFiles, setAiUploadedFiles] = useState<any[]>([]);
  // 添加文件上传状态
  const [uploadStatus, setUploadStatus] = useState<{
    isUploading: boolean;
    fileName: string;
  }>({ isUploading: false, fileName: '' });
  const temp_session_id = 'e557bd4f-269d-4a33-9b70-76286d1a8749'
  // 滚动引用
  const chatScrollRef = useRef<HTMLDivElement>(null);
  // 引用
  const aiFileInputRef = useRef<HTMLInputElement>(null);
  streamApiService.setConfigParams({
    baseURL: configApi.baseURL || '/langchain-backend',
    serviceRunPath: configApi.serviceRunPath || '/service_run_stream'
  });
  // 聊天功能处理函数
  const scrollChatToBottom = () => {
    setTimeout(() => {
      if (chatScrollRef.current) {
        chatScrollRef.current.scrollTop = chatScrollRef.current.scrollHeight;
      }
    }, 100);
  };

  const handleChatSend = async () => {
    if (!chatInput.trim() || isChatting) return;

    const userMessage = {
      type: 'user' as const,
      content: chatInput.trim(),
      timestamp: new Date().toLocaleString('zh-CN')
    };
    // 提取已上传文件的docId列表
    const docIds = aiUploadedFiles.map(file => file.docId).filter(Boolean);
    // 将用户问题添加到AI解读内容中
    const userHtml = `<div style="margin-top: 20px; padding: 12px; background: #f0f9ff; border-left: 4px solid #3b82f6; border-radius: 6px;">
        <div style="font-weight: 600; color: #1e40af; margin-bottom: 6px;">您的问题：</div>
        <div style="color: #1e40af;">${userMessage.content}</div>
        <div style="font-size: 12px; color: #6b7280; margin-top: 6px;">${userMessage.timestamp}</div>
      </div>`;

    // 立即显示"AI正在思考"状态
    const thinkingHtml = `<div id="ai-thinking-${Date.now()}" style="margin-top: 12px; padding: 12px; background: #f8fafc; border-left: 4px solid #10b981; border-radius: 6px;">
        <div style="font-weight: 600; color: #047857; margin-bottom: 6px; display: flex; align-items: center; gap: 8px;">
          <div class="animate-spin w-3 h-3 border-2 border-green-500 border-t-transparent rounded-full"></div>
          AI正在思考您的问题...
        </div>
        <div style="color: #6b7280; font-size: 14px;">正在分析研报内容，为您准备专业回答</div>
      </div>`;

    setAiAnalysis(prev => prev + userHtml + thinkingHtml);
    setChatHistory(prev => [...prev, userMessage]);
    setChatInput('');
    setIsChatting(true);
    setChatStreamReply('');

    const messageText = `${chatInput.trim()}`;

    try {
      await streamApiService.sendMessageStream(
        messageText,
        (chunk: string, accumulated: string, phase?: 'reasoning' | 'llm', messageType?: string) => {
          // 处理任务进度消息，更新思考状态
          if (messageType === 'task_start' || messageType === 'planning_start' || messageType === 'sub_task_progress') {
            // 更新"正在思考"状态显示具体进度
            setAiAnalysis(prev => {
              const lastThinkingIndex = prev.lastIndexOf('<div id="ai-thinking-');
              if (lastThinkingIndex !== -1) {
                const beforeThinking = prev.substring(0, lastThinkingIndex);
                const progressHtml = `<div id="ai-thinking-${Date.now()}" style="margin-top: 12px; padding: 12px; background: #f8fafc; border-left: 4px solid #10b981; border-radius: 6px;">
                    <div style="font-weight: 600; color: #047857; margin-bottom: 6px; display: flex; align-items: center; gap: 8px;">
                      <div class="animate-spin w-3 h-3 border-2 border-green-500 border-t-transparent rounded-full"></div>
                      AI正在处理...
                    </div>
                    <div style="color: #6b7280; font-size: 14px;">${chunk}</div>
                  </div>`;
                return beforeThinking + progressHtml;
              }
              return prev;
            });
          }
          // 只在LLM阶段（或没有phase信息时）更新UI显示流式内容
          else if (phase === 'llm' || (!phase && messageType === 'llm_output')) {
            const renderedContent = renderMarkdownStreaming(accumulated);
            // 实时更新"正在思考"状态为流式回复
            setAiAnalysis(prev => {
              const lastThinkingIndex = prev.lastIndexOf('<div id="ai-thinking-');
              if (lastThinkingIndex !== -1) {
                const beforeThinking = prev.substring(0, lastThinkingIndex);
                const streamingHtml = `<div id="ai-thinking-${Date.now()}" style="margin-top: 12px; padding: 12px; background: #f8fafc; border-left: 4px solid #10b981; border-radius: 6px;">
                    <div style="font-weight: 600; color: #047857; margin-bottom: 6px; display: flex; align-items: center; gap: 8px;">
                      <div class="animate-spin w-3 h-3 border-2 border-green-500 border-t-transparent rounded-full"></div>
                      AI正在回复...
                    </div>
                    <div>${renderedContent}<div/>
                  </div>`;
                console.log(beforeThinking + streamingHtml)
                return beforeThinking + streamingHtml;
              }
              return prev;
            });
          }
        },
        (fullMessage: StreamMessage) => {
          const finalContent = renderMarkdownStreaming(fullMessage.text);
          // 将AI回复添加到AI解读内容中，替换"正在思考"状态
          const aiHtml = `<div style="margin-top: 12px; padding: 12px; background: #f8fafc; border-left: 4px solid #10b981; border-radius: 6px;">
              <div style="font-weight: 600; color: #047857; margin-bottom: 6px;">AI回复：</div>
              <div>${finalContent}</div>
              <div style="font-size: 12px; color: #6b7280; margin-top: 6px;">${new Date().toLocaleString('zh-CN')}</div>
            </div>`;

          // 移除"正在思考"状态并添加最终回复
          setAiAnalysis(prev => {
            // 移除最后一个"正在思考"的div
            const lastThinkingIndex = prev.lastIndexOf('<div id="ai-thinking-');
            if (lastThinkingIndex !== -1) {
              const beforeThinking = prev.substring(0, lastThinkingIndex);
              return beforeThinking + aiHtml;
            }
            return prev + aiHtml;
          });

          setChatStreamReply('');
          setChatHistory(prev => [...prev, {
            type: 'ai',
            content: finalContent,
            timestamp: new Date().toLocaleString('zh-CN')
          }]);
          setIsChatting(false);
        },
        (error: string) => {
          message.error(`对话失败: ${error}`);

          // 出错时也要移除"正在思考"状态
          setAiAnalysis(prev => {
            const lastThinkingIndex = prev.lastIndexOf('<div id="ai-thinking-');
            if (lastThinkingIndex !== -1) {
              const beforeThinking = prev.substring(0, lastThinkingIndex);
              const errorHtml = `<div style="margin-top: 12px; padding: 12px; background: #fef2f2; border-left: 4px solid #ef4444; border-radius: 6px;">
                  <div style="font-weight: 600; color: #dc2626; margin-bottom: 6px;">回复失败</div>
                  <div style="color: #dc2626; font-size: 14px;">抱歉，AI暂时无法回答您的问题，请稍后重试</div>
                </div>`;
              return beforeThinking + errorHtml;
            }
            return prev;
          });

          setIsChatting(false);
          setChatStreamReply('');
        },
        '刘一',
        temp_session_id,
        docIds,
        configApi.framework?configApi.framework:{},
        'report_analyze_tool'
      );
    } catch (error) {
      message.error('对话请求失败');

      // 出错时也要移除"正在思考"状态
      setAiAnalysis(prev => {
        const lastThinkingIndex = prev.lastIndexOf('<div id="ai-thinking-');
        if (lastThinkingIndex !== -1) {
          const beforeThinking = prev.substring(0, lastThinkingIndex);
          const errorHtml = `<div style="margin-top: 12px; padding: 12px; background: #fef2f2; border-left: 4px solid #ef4444; border-radius: 6px;">
              <div style="font-weight: 600; color: #dc2626; margin-bottom: 6px;">连接失败</div>
              <div style="color: #dc2626; font-size: 14px;">网络连接异常，请检查网络后重试</div>
            </div>`;
          return beforeThinking + errorHtml;
        }
        return prev;
      });

      setIsChatting(false);
      setChatStreamReply('');
    }
  };

  const handleStopChat = () => {
    if (isChatting) {
      streamApiService.stopStream();
      setIsChatting(false);
      setChatStreamReply('');
    }
  };

  // AI文件上传处理
  const handleAiFileUpload = async (file: File) => {
    // 检查文件类型
    if (!validateFileType(file)) {
      message.error(getFileTypeErrorMessage());
      return false;
    }

    // 检查文件大小
    if (!validateFileSize(file, 10)) {
      message.error(getFileSizeErrorMessage(10));
      return false;
    }

    // 检查总上传文件大小
    const totalSize = aiUploadedFiles.reduce((sum, f) => sum + (f.size || 0), 0) + file.size;
    if (totalSize > 10 * 1024 * 1024) {
      message.error('所有已上传文件总大小不能超过10M，请删除部分文件后再上传。');
      return false;
    }

    // 设置上传状态
    setUploadStatus({ isUploading: true, fileName: file.name });

    try {
      const result = await uploadFile(file, temp_session_id);

      const newFile = {
        id: Date.now(),
        name: result.filename || file.name,
        originalName: file.name,
        size: file.size,
        type: file.type,
        docId: result.docId,
        uploadedAt: new Date().toISOString(),
        serviceId: 'auto',
        sessionId: temp_session_id || streamApiService.getSessionId(),
      };

      setAiUploadedFiles(prev => [...prev, newFile]);
      message.success({ content: `文件 ${file.name} 上传成功`, key: 'upload' });
    } catch (error) {
      console.error('Upload error:', error);
      message.error({
        content: `上传失败: ${error instanceof Error ? error.message : '未知错误'}`,
        key: 'upload'
      });
    } finally {
      setUploadStatus({ isUploading: false, fileName: '' });
    }

    return false;
  };

  // 移除AI上传的文件
  const handleRemoveAiFile = (fileId: number) => {
    setAiUploadedFiles(prev => prev.filter(file => file.id !== fileId));
  };


  useEffect(() => {
    scrollChatToBottom();
  }, [chatHistory, chatStreamReply]);

  return (
    <div className="flex-1 flex overflow-hidden" style={style}>
      {/* AI解读 */}
      <div className="bg-white rounded-lg overflow-hidden flex flex-col" style={{ width: '100%' }}>
        <div className="border-b px-6 py-4 flex-shrink-0">
          <div className="flex items-center gap-2">
            <RobotOutlined className="text-blue-500" />
            <Title level={5} className="!mb-0">{title}</Title>
          </div>
        </div>

        {/* AI解读内容区域 - 占满上半部分 */}
        <div className="flex-1 overflow-y-auto p-6">
          {isStreaming && (
            <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
              <div className="flex items-center gap-2">
                <div className="animate-spin w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full"></div>
                <Text className="text-blue-600">AI正在解读研报内容，请稍候...</Text>
              </div>
            </div>
          )}

          <div
            className="text-sm prose prose-sm max-w-none"
            dangerouslySetInnerHTML={{ __html: renderMarkdownStreaming(aiAnalysis || '', 'send') || '<div style="color: #6b7280; font-style: italic;">正在生成回复...</div>' }}
          />

          {!isStreaming && aiAnalysis && (
            <div className="mt-6 pt-4 border-t border-gray-200">
              <Text type="secondary" className="text-xs">
                内容由AI生成，不构成投资建议，请谨慎参考
              </Text>
            </div>
          )}
        </div>

        {/* 底部输入区域 - 固定在底部 */}
        <div className="flex-shrink-0 border-t border-gray-200 bg-white">
          {/* AI功能开关 */}


          {/* 上传状态提示 */}
          {uploadStatus.isUploading && (
            <div className="mb-2 px-3 py-2 bg-blue-50 rounded-md border border-blue-200">
              <div className="flex items-center gap-2">
                <div className="animate-spin w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full"></div>
                <span className="text-sm text-blue-700">
                  正在上传: {uploadStatus.fileName}
                </span>
              </div>
            </div>
          )}
          {/* 组件自定义显示内容 */}
          <div className="mb-2 p-2 bg-gray-50 rounded border"
            dangerouslySetInnerHTML={{ __html: renderMarkdownStreaming(propContent || '') || '' }}></div>
          {/* 已上传文件显示 */}
          {aiUploadedFiles.length > 0 && (
            <div className="mb-2 p-2 bg-gray-50 rounded border">
              <div className="text-xs text-gray-600 mb-1">已上传文件:</div>
              <div className="space-y-1">
                {aiUploadedFiles.map((file) => (
                  <div key={file.id} className="flex items-center gap-2 text-xs">
                    <PictureOutlined className="text-blue-500" />
                    <span className="flex-1 truncate" title={file.originalName || file.name}>
                      {file.originalName || file.name}
                    </span>
                    <Button
                      type="text"
                      size="small"
                      onClick={() => handleRemoveAiFile(file.id)}
                      className="text-gray-400 hover:text-red-500 p-0"
                      icon={<CloseOutlined />}
                      title="移除文件"
                    />
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 输入框和按钮 */}
          <div className="p-4">
            <div className="flex gap-2">
              {/* 文件上传按钮 */}
              {uploadable ? (
                <Button
                  icon={<CloudUploadOutlined />}
                  onClick={() => aiFileInputRef.current?.click()}
                  disabled={isAutoReplying || isStreaming || uploadStatus.isUploading}
                  title="上传文件（支持PDF、Word、PPT、Excel、图片等）"
                  className="flex-shrink-0"
                />
              ) : ''}


              <TextArea
                value={chatInput}
                onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setChatInput(e.target.value)}
                placeholder="基于研报内容提问..."
                autoSize={{ minRows: 1, maxRows: 2 }}
                onPressEnter={(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
                  if (!e.shiftKey) {
                    e.preventDefault();
                    handleChatSend();
                  }
                }}
                disabled={isChatting}
                className="flex-1 text-sm"
              />

              {/* 发送/终止按钮 */}
              {isChatting ? (
                <Button
                  danger
                  icon={<StopOutlined />}
                  onClick={handleStopChat}
                  title="终止对话"
                  className="flex-shrink-0"
                  size="small"
                />
              ) : (
                <Button
                  type="primary"
                  icon={<SendOutlined />}
                  onClick={handleChatSend}
                  disabled={!chatInput.trim()}
                  title="Enter 发送 | Shift + Enter 换行"
                  className="flex-shrink-0 bg-blue-500"
                  size="small"
                />
              )}
            </div>
          </div>

          {/* 隐藏的文件输入 */}
          <input
            ref={aiFileInputRef}
            type="file"
            accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.jpg,.jpeg,.png,.txt,.csv,.md"
            style={{ display: 'none' }}
            onChange={(e) => {
              const file = e.target.files?.[0];
              if (file) {
                handleAiFileUpload(file);
              }
              e.target.value = '';
            }}
          />
          
        </div>
      </div>
    </div>
  );
};

export default AIChatModel;